package business

import (
	"errors"
	"strings"

	"ginBasic/app"
	"ginBasic/app/common/lib"
	"ginBasic/app/common/model"
	"ginBasic/app/common/model/filter"
)

var Manager = new(ManagerBus)

type ManagerBus struct {
	BaseBus
}

func (b ManagerBus) GetUserInfoList(req *filter.ManagerFilterReq) ([]interface{}, int, error) {

	where := "1=1"
	// 查询条件
	if req != nil {
		// 用户名
		if req.Username != "" {
			where += " AND username like '%" + req.Username + "%'"
		}
		if req.Mobile != "" {
			where += " AND mobile like '%" + req.Mobile + "%'"
		}
	}
	managerList, total, err := model.ManagerModel.List(where, req.Page, req.PageSize)

	List := make([]interface{}, 0)
	for _, v := range managerList {
		List = append(List, map[string]interface{}{
			"id":         v.Id,
			"username":   v.Username,
			"mobile":     v.Mobile,
			"email":      v.Email,
			"role":       v.Role.Title,
			"status":     v.Status,
			"addTime":    lib.UnixToTime(v.AddTime),
			"updateTime": lib.UnixToTime(v.UpdateTime),
		})
	}
	return List, total, err

}

func (b ManagerBus) Add(req *model.Manager) (bool, error) {
	_, err := model.ManagerModel.Add(req)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (b ManagerBus) Edit(req *model.Manager) (bool, error) {
	_, err := model.ManagerModel.Edit(req)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (b ManagerBus) GetUserInfoById(id int) model.Manager {
	userInfo := model.Manager{}
	userInfo = model.ManagerModel.GetUserById(id)
	return userInfo
}

func (b ManagerBus) Delete(ids string) (int64, error) {
	idsArr := strings.Split(ids, ",")
	//判断是否存在超级管理员
	_, found := app.Find(idsArr, "1")
	if found {
		return 0, errors.New("admin用户不能删除")
	}
	res, err := model.ManagerModel.Delete(idsArr)
	if res {
		count := int64(len(idsArr))
		return count, nil
	} else {
		return 0, err
	}
}

func (b ManagerBus) UpdateStatus(req *model.Manager) (bool, string) {

	if req.Id == 1 {
		return false, "admin用户不能关闭"
	}
	_, err := model.ManagerModel.UpdateStatus(req)
	if err != nil {
		return false, err.Error()
	} else {
		return true, "操作成功"
	}
}
